﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static VerficationsWPF.Common;

namespace VerficationsWPF.Verifications
{
    /// <summary>
    /// TaskWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskDemoWindow : Window
    {
        public TaskDemoWindow()
        {
            InitializeComponent();
        }

        Task<int> TaskMethod1()
        {
            return Task.FromResult(2);
        }

        async Task<int> TaskMethod2Async(int v = 100)
        {
            var task = await Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    //res = v + x + 1; 
                    return 1;
                }
            );

            Debug.WriteLine("await");
            // await task;
            Debug.WriteLine("exit await.");
            return task + v;
        }

        private async void btnSimpleTest_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("TaskMethod1: " + TaskMethod1().Result);

            var res = await Task.Run(() =>
            {
                Thread.Sleep(1000);
                //res = v + x + 1; 
                return 1;
            });
            Debug.WriteLine("res = " + res);

            // 2022/05/12 调用 TaskMethod2Async() 就会卡死，原因未知
            var res1 = await TaskMethod2Async();
            Debug.WriteLine("TaskMethod2_async: " + res1);
        }

        private async void btnAsyncTest1_Click(object sender, RoutedEventArgs e)
        {
            btnAsyncTest1.IsEnabled = false;
            LongTaskTextBlock.Text = "Starting long task";

            var result = await Task.Run(() =>
            {
                Thread.Sleep(2000);
                return 0;// "Completed long task";
            });

            btnAsyncTest1.IsEnabled = true;
            LongTaskTextBlock.Text = $"result: {result}";
        }

        private void btnTaskTest1_Click(object sender, RoutedEventArgs e)
        {
            // Task<int[]> 生成示例，完全可以继续传递给窗体
            TaskFactory taskFactory = new TaskFactory();
            List<Task<int[]>> tasks = new List<Task<int[]>>();

            for (int i = 0; i < 10; i++)
            {
                Func<int[]> fi = () =>
                {
                    int[] values = new int[10];
                    for (int i = 0; i < values.Length; i++)
                    {
                        Thread.Sleep(Random.Shared.Next(0, 1000));
                        values[i] = Random.Shared.Next(0, 200);
                        print($"Task {i}: values[i] = {values[i]}.");
                    }
                    return values;
                };

                // Task t <== Task<int[]> 是可行的，不过后面需要转换
                Task t = taskFactory.StartNew(fi);
                if (t is Task<int[]> t_array)
                {
                    //tasks.Add(t as Task<int[]> ?? new Task<int[]>(fi));
                    tasks.Add(t_array);
                }
            }

            print($"Tasks Count: {tasks.Count}");
        }

        private void btnTaskConversion_Click(object sender, RoutedEventArgs e)
        {
            // 这个示例说明 Task<int[]> 是 Task 的派生类
            TaskFactory taskFactory = new TaskFactory();
            Func<int[]> fi = () =>
            {
                int[] values = new int[10];
                for (int i = 0; i < values.Length; i++)
                {
                    Thread.Sleep(Random.Shared.Next(0, 1000));
                    values[i] = Random.Shared.Next(0, 200);
                    print($"Task {i}: values[i] = {values[i]}.");
                }
                return values;
            };

            // Task t <== Task<int[]> 是可行的，不过后面需要转换
            Task t = taskFactory.StartNew(fi);

            t.Wait();

            if (t is Task<int[]> t1)
            {
                print($"t1.Result.Sum: {t1.Result.Sum()}");
            }
            else
            {
                print("done with no results.");
            }

        }

        private void btnTaskWindow_Click(object sender, RoutedEventArgs e)
        {
            var w1 = new AsyncTasRunWindow();
            w1.RunAndShow(() => { Thread.Sleep(2000); return 0; });
            if(w1.ResultTask is Task<int> w2)
            {
                print("Result: " + w2);
            }
        }
    }
}
